export default class LazyLoad {
  constructor(context, opt = {}) {
    this.page = context;

    this.classNote = opt.classNote || 'item-'
    this.initNum = opt.initNum || 8
    this.limit = opt.limit || 8

    this.intersectionObserver = {}

    this.page.setData({
      lazpage: this.initNum
    })
    if (!this.isSupport()) console.error('wx.createIntersectionObserver is not a function')
  }

  observe() {
    if (!this.isSupport()) return
    const that = this
    this.intersectionObserver = wx.createIntersectionObserver();
    this.intersectionObserver.relativeToViewport({ bottom: 140 }).observe(this.classNote + this.page.data.lazpage, (res) => {
      if (res.boundingClientRect.top > 0) {
        that.intersectionObserver.disconnect()
        setTimeout(() => {
          that.page.setData({
            lazpage: that.page.data.lazpage + that.limit
          })
        }, 1000)
      }
    })
  }

  isSupport() {
    return !!wx.createIntersectionObserver
  }
}